<?php
class Page extends PageBaseUpdate {

	public function InitializeComponent(){
		parent::InitializeComponent();
		$this->ClassName = "Rol";
		$this->LocalControls = "Nombre";
	}

	public function onLoad($param){
		parent::onLoad($param);
		if(!$this->IsPostBack){
            $id = $this->Request["id"];
            if(!is_null($id)){
                $this->CargarRol($id);
            }else{

            }
			$this->LoadData();
        }
    }

	protected function LoadData(){
		$this->cklPagina->DataSource = PaginaPeer::PaginasHome();
		$this->cklPagina->dataBind();
	}

	public function cvNombre_OnServerValidate($sender, $param){
        $nombre = $param->Value;

		$c = new Criteria();
		$c->add(RolPeer::NOMBRE, $nombre);

        //veo si es un update que no controle por su propio id
        $id = $this->Request["id"];

        if(!is_null($id))$c->addAnd(RolPeer::IDROL, $id, Criteria::NOT_EQUAL);

		$categoria = RolPeer::doSelectOne($c);
		$param->IsValid = is_null($categoria);
	}

	protected function CargarRol($id){
		$rol = RolPeer::retrieveByPK($id);
		$rolpagina = $rol->getRolpaginas();
        $paginasToBind = array();

        foreach($rolpagina as $p){
            $paginasToBind[] = $p->getIdpagina();
        }

        $this->cklPagina->SelectedValues = $paginasToBind;
	}

	public function btnAceptar_OnClick($sender, $param)
	{
		if($this->IsValid){
			$id = $this->Save();
			$rol = RolPeer::retrieveByPK($id);
			$rolpagina = $rol->getRolpaginas();

			foreach($rolpagina as $p){
				$p->delete();
			}

			$paginas = $this->cklPagina->SelectedValues;

			for($i=0; $i<count($paginas); $i++){
				$rolpagina = new Rolpagina();
				$rolpagina->setIdrol($id);
				$rolpagina->setIdpagina($paginas[$i]);
				$rolpagina->save();
			}

			$this->Back("?page=Rol.Home");
		}
	}

	public function btnCancelar_OnClick($sender, $param){
       	$this->Back("?page=Rol.Home");
    }
}
?>